package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.activity.ClassListActivity.FileManageAdapter;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.Classinfo;
import com.ycsj.goldmedalnewconcept.bean.ClassinfoResponse;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;

//学生档案
public class StudentFileActivity extends Activity implements OnClickListener {

	private GridView gv_filemanage;
	private FileManageAdapter mAdapter;
	private List<Classinfo> list = new ArrayList<Classinfo>();
	private List<Classinfo> list2 = new ArrayList<Classinfo>();
	private List<String> iconList = new ArrayList<String>();
	private List<String> nameList = new ArrayList<String>();
	
	private String account;
	private ImageView iv_back;
	private int size;
	int iconNumn = 0;
	private PopupWindow popup;
	private int width;
	private int height2;
	private TextView tv_empty;
	private TextView tv_addstudent;
	private String iconJson;
	private String nameJson;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_studentfile);
		initView();
		setOnListener();
		initData();
	}

	int[] classIcons = { R.drawable.class1, R.drawable.class2,
			R.drawable.class3, R.drawable.class4, R.drawable.class5,
			R.drawable.class6, R.drawable.class7, R.drawable.class8,
			R.drawable.class9, R.drawable.class10, };

	private void initView() {
		gv_filemanage = (GridView) findViewById(R.id.gv_filemanage);
		tv_empty = (TextView) findViewById(R.id.tv_empty);
		tv_addstudent = (TextView) findViewById(R.id.tv_addstudent);
		iv_back = (ImageView) findViewById(R.id.iv_back);
	}

	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		
		initData();
		super.onRestart();
	}
	private void initData() {
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels;
		height2 = metric.heightPixels;
		account = SPUtil.getString(this, "account", "");
		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "3");
		builder.add("userID", account);
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL + "AppClassMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();

				String json = arg0.body().string();
				ClassinfoResponse fromJson = gson.fromJson(json,
						ClassinfoResponse.class);
				Log.e("test11", json);
				size = 0;
				if (fromJson != null) {
					if ("-1".equals(fromJson.state)
							) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {

//								tv_empty.setVisibility(tv_empty.VISIBLE);
							}
						});
						return;
					}
					if (fromJson.size != ""&&fromJson.size!=null) {
						size = Integer.parseInt(fromJson.size);
						list = new ArrayList<Classinfo>();
						JSONTokener jsonParser = new JSONTokener(json);
						// 此时还未读取任何json文本，直接读取就是一个JSONObject对象。
						try {
							JSONObject classJson = (JSONObject) jsonParser
									.nextValue();
							for (int i = 0; i < size; i++) {
								JSONObject classinfo0 = classJson
										.getJSONObject("classinfo" + i);  

								String id = classinfo0.getString("id");
								String userID = classinfo0.getString("userID");
								String icon = classinfo0.getString("icon");
								String num = classinfo0.getString("num");
								String name = classinfo0.getString("name");
								String studentNum = classinfo0
										.getString("studentNum");
								Classinfo classinfo = new Classinfo(id, userID,
										icon, num, name, studentNum);
								
								list.add(classinfo);
							}
							
							for (int i = 0; i < list.size(); i++) {
								iconList.add(list.get(i).icon);
								nameList.add(list.get(i).name);
							}
							iconJson = gson.toJson(iconList);
							nameJson = gson.toJson(nameList);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

				runOnUiThread(new Runnable() {
					@Override
					public void run() {

						mAdapter = new FileManageAdapter(list, getBaseContext());
						gv_filemanage.setAdapter(mAdapter);
						gv_filemanage
								.setOnItemClickListener(new OnItemClickListener() {

									@Override
									public void onItemClick(
											AdapterView<?> parent, View view,
											int position, long id) {
										// TODO Auto-generated method stub
										if (position == list.size()) {

											// 创建PopupWindow对象
											LayoutInflater mInflater = LayoutInflater
													.from(StudentFileActivity.this);
											ViewGroup rootView = (ViewGroup) mInflater
													.inflate(
															R.layout.popwindow_editclass,
															null);
											rootView.setLayoutParams(new LayoutParams(
													LayoutParams.WRAP_CONTENT,
													LayoutParams.WRAP_CONTENT));
											LinearLayout ll_main = (LinearLayout) rootView
													.findViewById(R.id.ll_main);
											ImageView iv_close_editclass = (ImageView) rootView
													.findViewById(R.id.iv_close_editclass);
											final ImageView iv_classicon = (ImageView) rootView
													.findViewById(R.id.iv_classicon);
											ImageView iv_classicon_left = (ImageView) rootView
													.findViewById(R.id.iv_classicon_left);
											ImageView iv_classicon_right = (ImageView) rootView
													.findViewById(R.id.iv_classicon_right);
											final EditText et_inputclassname = (EditText) rootView
													.findViewById(R.id.et_inputclassname);
											Button bt_updateclassinfo = (Button) rootView
													.findViewById(R.id.bt_updateclassinfo);
											Animation slide_up_in = AnimationUtils
													.loadAnimation(
															StudentFileActivity.this,
															R.anim.slide_up_in);
											ll_main.startAnimation(slide_up_in);

											popup = new PopupWindow(
													rootView,
													width,
													WindowManager.LayoutParams.WRAP_CONTENT,
													true);
											popup.setContentView(rootView);

											// setContentView之前一定要设置宽高，否则不显示
											popup.setWidth(width * 3 / 4);
											// popup.setHeight(height2*6/15);
											// popup.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
											popup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
											// 去掉默认的背景
											popup.setBackgroundDrawable(new ColorDrawable(
													android.R.color.transparent));

											// 点击空白处的时候PopupWindow会消失
											// popup.setTouchable(true);
											// 如果focusable为false，在一个Activity弹出一个PopupWindow，按返回键，由于PopupWindow没有焦点，会直接退出Activity。如果focusable为true，PopupWindow弹出后，所有的触屏和物理按键都有PopupWindows处理。
											popup.setOutsideTouchable(false);
											popup.setFocusable(true);

											popup.showAtLocation(
													(View) gv_filemanage
															.getParent(),
													Gravity.NO_GRAVITY,
													width / 9, height2 * 3 / 10);
											//点击保存
											bt_updateclassinfo
													.setOnClickListener(new OnClickListener() {

														@Override
														public void onClick(
																View v) {
															String trim = et_inputclassname
																	.getText()
																	.toString()
																	.trim();
															for (int i = 0; i < list.size(); i++) {
																if(trim.equals(list.get(i).name)){
																	Toast.makeText(getBaseContext(), 
																			"班级名不可重复", 0)
																	.show();
																	return;
																}
															}
															
															if ("".equals(trim)) {
																Toast.makeText(getBaseContext(), 
																		"班级名称不能为空", 0)
																.show();
																return;
															} else {
																popup.dismiss();
							//创建班级								
							OkHttpClient mOkHttpClient = new OkHttpClient();
							 // mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
								FormEncodingBuilder builder = new FormEncodingBuilder();
								builder.add("type", "3");
								builder.add("userID", account);
							    builder.add("icon", (iconNumn+1)+"");
							    builder.add("name", trim);

								Request request = new Request.Builder()
										.url(Constant.servlet_MessageController).post(builder.build())
										.build();
	//http://www.moregolden.com/ycsj_jpxgn/servlet/MessageController?type=3&userID=18672626702&icon=1&name=JPXGN7
								mOkHttpClient.newCall(request).enqueue(new Callback() {

									@Override
									public void onFailure(Request arg0, IOException arg1) {
										runOnUiThread(new Runnable() {
											@Override
											public void run() {
												Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
														.show();
											}
										});
									}

									@Override
									public void onResponse(Response arg0) throws IOException {
										// 解析Json数据，保存登录状态及身份信息
										Gson gson = new Gson();

										String json = arg0.body().string();
										Log.i("test","返回的班级信息是:"+json);
										AttResponse fromJson = gson.fromJson(json,
												AttResponse.class);
										 Log.e("test", json);
										if (fromJson != null) {
											if ("-1".equals(fromJson.state)
													|| "0".equals(fromJson.state)) {
											}
											if("1".equals(fromJson.state)){
												
												runOnUiThread(new Runnable() {
													@Override
													public void run() {
														initData();
														Toast.makeText(getBaseContext(), "创建成功！", 0)
														.show();
													}
												});
											}
										}
									}
								});
															}
														}
													});

											iv_classicon
													.setImageResource(classIcons[iconNumn]);
											iv_classicon_right
													.setOnClickListener(new OnClickListener() {
														@Override
														public void onClick(
																View v) {
															if (iconNumn < classIcons.length - 1) {

																iconNumn = iconNumn + 1;
																iv_classicon
																		.setImageResource(classIcons[iconNumn]);
															}
														}
													});
											iv_classicon_left
													.setOnClickListener(new OnClickListener() {
														@Override
														public void onClick(
																View v) {
															if (iconNumn > 0) {
																iconNumn = iconNumn - 1;
																iv_classicon
																		.setImageResource(classIcons[iconNumn]);
															}
														}
													});
											iv_close_editclass
													.setOnClickListener(new OnClickListener() {
														@Override
														public void onClick(
																View v) {
															popup.dismiss();
														}
													});
										} else {
											Intent intent = new Intent(
													StudentFileActivity.this,
													ClassInfoActivity.class);
											intent.putExtra("classid",
													list.get(position).id);
											intent.putExtra("classnum",
													list.get(position).num);
											intent.putExtra("classname",
													list.get(position).name);
											intent.putExtra("icon", list.get(position).getIcon());
											intent.putExtra("names",nameJson);
											intent.putExtra("nums",iconJson);
											
											startActivity(intent);
										}
									}
								});
					}
				});
			}
		});

	}

	private void setOnListener() {
		iv_back.setOnClickListener(this);
		tv_addstudent.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_addstudent:
			//添加学生
			
			Intent intent = new Intent(this, CreatStudentActivity.class);
			startActivity(intent);
			break;
		}
	}

	class FileManageAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private List<Classinfo> list;

		public FileManageAdapter(List<Classinfo> list, Context context) {
			super();
			this.list = list;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			if (null != list) {
				return list.size() + 1;
			} else {
				return 0;
			}
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.gv_filemanage_item,
						null);
				viewHolder = new ViewHolder();
				viewHolder.name = (TextView) convertView
						.findViewById(R.id.name);
				viewHolder.icon = (ImageView) convertView
						.findViewById(R.id.image);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			if (position == list.size()) {
				viewHolder.name.setVisibility(View.GONE);
				viewHolder.icon.setVisibility(View.VISIBLE);
			} else {
				viewHolder.name.setVisibility(View.VISIBLE);
				viewHolder.icon.setVisibility(View.GONE);
				viewHolder.name.setText(list.get(position).getName());

			}
			return convertView;
		}
	}

	class ViewHolder {
		public TextView name;
		public ImageView icon;
	}
}
